<style scoped>
::v-deep .custom-dialog {
  height: 90% !important;
}
:deep(.custom-dialog .el-dialog__footer) {
  padding: 0 !important;
  position: relative;
  min-height: 40px;
}
.dialog-footer-right {
  position: absolute;
  right: 10px;
  bottom: 10px;
}
.popup-bottom .el-row {
  display: flex;
  height: 100%;
  margin: 0 -5px; /* 抵消列间距的边距 */
}

.popup-bottom .el-col {
  flex: 1; /* 三列均分宽度 */
  padding: 0 5px; /* 列间距 */
  min-width: 0; /* 防止内容溢出 */
}

/* 确保每个图表容器填满空间 */
.bottom-left,
.bottom-middle,
.bottom-right {
  height: 100%;
}

/* 微调图表容器内边距 */
.popup-bottom .el-table {
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
}

/* 响应式调整（可选） */
@media (max-width: 992px) {
  .popup-bottom .el-row {
    flex-wrap: wrap;
  }
  .popup-bottom .el-col {
    flex: 0 0 100%;
    padding: 5px 0;
  }
}

.inline-form {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.form-item {
  flex: 0 0 auto; /* 不伸缩不收缩 */
}

/* 调整Element组件默认样式 */
.inline-form .el-select,
.inline-form .el-input {
  width: 200px; /* 统一宽度，可按需调整 */
}

.table-container {
  width: 100%;
  margin-top: 20px;
  overflow: hidden;
}

/* 确保表格宽度与图表一致 */
.popup-middle,
.table-container {
  width: 100%;
  height: 200px;
}

/* 表格滚动条样式 */
.el-table {
  width: 100% !important;
}

.el-table__body-wrapper {
  overflow-y: auto !important;
}

/* 其他样式保持不变 */
::v-deep .custom-dialog {
  height: 90% !important;
}
</style>


<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="elForm"
      size="small"
      :inline="true"
      label-width="100px"
    >
      <el-row>
        <el-form-item label="插座编号:" prop="devid">
          <el-input
            v-model="queryParams.devid"
            placeholder="请输入插座编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="在线状态" prop="jobGroup">
          <el-select
            v-model="queryParams.onlineStatus"
            placeholder="在线状态"
            clearable
          >
            <el-option label="在线" value="1"></el-option>
            <el-option label="离线" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否置顶" prop="isTopMap">
          <el-select
            v-model="queryParams.isTop"
            placeholder="是否置顶"
            clearable
          >
            <el-option label="是" value="Y"></el-option>
            <el-option label="否" value="N"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="网络状态" prop="networkType">
          <el-select
            v-model="queryParams.networkType"
            placeholder="请选择设备网络状态"
            clearable
            :style="{ width: '100%' }"
          >
            <el-option label="TCP专线" value="1"></el-option>
            <el-option label="4G专线" value="2"></el-option>
            <el-option label="广域网专线" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="设备分组" prop="devGroupId">
          <el-select
            v-model="queryParams.devGroupId"
            placeholder="请选择设备分组"
            clearable
            filterable
            :style="{ width: '180px' }"
          >
            <el-option
              v-for="(item, index) in groupDict"
              :key="index"
              :label="item.devGroupName"
              :value="item.devGroupId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <!--
        <el-form-item label="所在区域" prop="areaId">
          <el-select
            v-model="queryParams.areaId"
            placeholder="请选择设备所在区域"
            clearable
            :style="{ width: '100%' }"
            filterable
          >
            <el-option
              v-for="(item, index) in areaInfoList"
              :key="index"
              :label="item.menuName"
              :value="item.menuId"
            ></el-option>
          </el-select>
        </el-form-item>
        -->
        <el-form-item label=" " prop="">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="submitSearchForm"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetForm"
            >重置</el-button
          >
        </el-form-item>
      </el-row>
    </el-form>
    <!-- <el-row>
            <el-form ref="elForm" :model="queryParams" size="medium" label-width="80px">
                <el-row style="margin-top: 20px;">
                    <el-col :span="5">
                        <el-form-item label="插座编号" prop="devid">
                            <el-input v-model="queryParams.devid" placeholder="请输入插座编号" clearable
                                :style="{ width: '100%' }"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="在线状态" prop="onlineStatus">
                            <el-select v-model="queryParams.onlineStatus" placeholder="请选择设备在线情况" clearable
                                :style="{ width: '100%' }">
                                <el-option label="在线" value="1"></el-option>
                                <el-option label="离线" value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="5">
                        <el-form-item label="网络状态" prop="networkType">
                            <el-select v-model="queryParams.networkType" placeholder="请选择设备网络状态" clearable
                                :style="{ width: '100%' }">
                                <el-option label="TCP专线" value="1"></el-option>
                                <el-option label="网关专线" value="2"></el-option>
                                <el-option label="广域网专线" value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="5">
                        <el-form-item label="所在区域" prop="areaId">
                            <el-select v-model="queryParams.areaId" placeholder="请选择设备所在区域" clearable
                                :style="{ width: '100%' }" filterable>
                                <el-option v-for="(item, index) in areaInfoList" :key="index" :label="item.menuName"
                                    :value="item.menuId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-form-item>
                        <el-button type="primary" style="margin-left: 10px;" icon="el-icon-search" size="mini"
                            @click="submitSearchForm">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetForm">重置</el-button>

                    </el-form-item>
                </el-row>
            </el-form>
        </el-row> -->
    <el-row>
      <el-table
        :data="devList"
        stripe
        style="width: 100%"
        row-key="tableId"
        lazy
        :load="loadDevLine"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          fixed
          label="插座编号"
          :key="exFlashKey"
          width="150"
          align="center"
          show-overflow-tooltip
        >
          <!-- <div v-if="scope.row.hasNewEx == 0">NO</div> -->
          <template slot-scope="scope">
            <!-- <el-badge v-if="scope.row.devExList && scope.row.devExList.length" :value="scope.row.devExList.length" @click.native="setExInfoDialog(scope.row.devExList)" class="badge" type="primary"  >{{scope.row.deviceId}}
          </el-badge>
          <span v-if="!(scope.row.devExList && scope.row.devExList.length)">{{scope.row.deviceId}}</span> -->
            <div v-if="scope.row.hasNewEx == false">
              {{ scope.row.deviceId }}
            </div>
            <div
              v-if="scope.row.hasNewEx == true"
              style="color: red"
              @click="setExInfoDialog(scope.row)"
            >
              {{ scope.row.deviceId }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="设备别名"
          prop="devName"
          width="120"
          align="center"
        ></el-table-column>

        <el-table-column
          prop="onlineStatus"
          label="在线状态"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.onlineStatus == 1"
              >在线</el-tag
            >
            &nbsp;&nbsp;
            <el-tag
              v-if="scope.row.workStatus == 1 && scope.row.onlineStatus == 1"
              >工作</el-tag
            >
            <el-tag type="info" v-if="scope.row.onlineStatus == 0">离线</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="isTop"
          label="是否置顶"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag type="primary" v-if="scope.row.isTop == 'Y'">{{
              computedIsTop(scope.row.isTop)
            }}</el-tag>
            <el-tag type="info" v-if="scope.row.isTop == 'N'">{{
              computedIsTop(scope.row.isTop)
            }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="devType" label="类型" width="120" align="center">
          <template slot-scope="scope">
            <span style="color: #00a400" v-if="scope.row.lineNum > 1"
              >多路</span
            >
            <span style="color: #888" v-else-if="!scope.row.optBut">单路</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          prop="relayStatus"
          label="继电器"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.relayStatus == 1">开</span>
            <span v-else-if="scope.row.relayStatus == 0">关</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="networkType"
          label="网络状态"
          width="120"
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.networkType == 1">WIFI</span>
            <span v-else-if="scope.row.networkType == 2">4G专线</span>
            <span v-else-if="scope.row.networkType == 3">广域网专线</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="voltage"
          label="电压（V）"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="electricCurrent"
          label="电流（A）"
          width="120"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="activePower"
          label="平均功率（W）"
          width="120"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="powerFactor"
          label="功率因素"
          width="120"
          align="center"
        >
        </el-table-column>

        <!-- <el-table-column prop="zip" label="平均功率(无)" width="120">
            </el-table-column> -->
        <el-table-column
          prop="frequency"
          label="频率"
          width="120"
          align="center"
        >
        </el-table-column>

        <el-table-column
          prop="dayEnergy"
          label="最近一天能耗"
          width="120"
          align="center"
        >
        </el-table-column>
        <!-- 
        <el-table-column
          prop="totalEnergy"
          label="累计用电量"
          width="120"
          align="center"
        >
        </el-table-column>
        -->

        <el-table-column
          prop="temperature"
          label="温度"
          width="120"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="modifyTime"
          label="更新时间"
          width="200"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!--
        <el-table-column
          prop="devInTheArea"
          label="所在区域"
          width="120"
          align="center"
        >
        </el-table-column>
         <el-table-column prop="exStaus" label="异常状态" width="120">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.exStaus != null">{{
              scope.row.exStaus
            }}</el-tag>
          </template>
        </el-table-column> 
        -->
        <el-table-column fixed="right" label="操作" width="340" align="center">
          <template slot-scope="scope" v-if="scope.row.optBut ? false : true">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-share"
              @click="sendCharCommand(scope.row)"
              >发送指令</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-tools"
              v-if="scope.row.lineNum <= 1"
              @click="loadDevMonitorParams(scope.row)"
              >参数配置</el-button
            >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-star-on"
              v-if="scope.row.isTop == 'N'"
              @click="changeTop('Y', scope.row.deviceId)"
              >置顶</el-button
            >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-star-off"
              v-if="scope.row.isTop == 'Y'"
              @click="changeTop('N', scope.row.deviceId)"
              >取消置顶</el-button
            >
            <el-button
              type="text"
              size="mini"
              icon="el-icon-star-off"
              @click="
                openTrackingPopup(scope.row.deviceId, scope.row.onlineStatus)
              "
              >实时追踪</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row style="margin-bottom: 20px">
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getDevList"
      />
    </el-row>
    <el-dialog title="未读异常列表" width="30%" :visible.sync="showExInfo">
      <el-table :data="exInfoList">
        <el-table-column prop="mac" label="mac地址"></el-table-column>
        <el-table-column prop="devExInfo" label="异常信息"></el-table-column>
        <el-table-column prop="occurTime" label="发生时间"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      title="字节命令"
      width="30%"
      :visible.sync="showByteCommandDialog"
    >
      <el-form label-width="100px">
        <el-form-item label="设备编号">
          <el-input type="text" v-model="cmd.deviceId" disabled></el-input>
        </el-form-item>
        <el-form-item label="发送指令">
          <el-select v-model="cmd.commandIdAndType">
            <el-option
              v-for="item in devCommandList"
              :key="item.id"
              :value="item.id + ',' + item.type"
              :label="item.name"
              placeholder="请选择"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="线路选择" v-if="lineList.length > 0">
          <el-select multiple v-model="cmd.lineIdList">
            <el-option
              v-for="group in lineList"
              :key="group.id"
              :label="group.deviceId"
              :value="group.lineNo"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="showByteCommandDialog = false">取消</el-button>
        <el-button @click="sendDevMeterCommand()">发送</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="监控参数配置"
      width="30%"
      :visible.sync="devMonitorParamDialog"
    >
      <el-form label-width="100px">
        <el-form-item label="设备编号">
          <el-input type="text" v-model="param.deviceId" disabled></el-input>
        </el-form-item>
        <el-form-item label="参数类型">
          <el-select @change="addInput" multiple v-model="param.paramIdList">
            <el-option-group
              v-for="group in devParamList"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="item in group.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item
          v-for="item in inputList"
          :key="item.name"
          :label="item.name"
        >
          <el-input type="text" v-model="item.threshold"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="devMonitorParamDialog = false">取消</el-button>
        <el-button @click="setDevMonitorParams()">发送</el-button>
      </div>
    </el-dialog>

    <!-- 实时追踪弹出层 -->
    <el-dialog
      @close="handleDialogClose"
      ref="trackingDialogSS"
      :visible.sync="trackingPopupVisible"
      title="实时追踪信息"
      @keyup.esc="exitFullScreen"
      width="90%"
      custom-class="custom-dialog"
    >
      <div class="popup-container">
        <!-- 上部分 -->
        <div class="popup-top inline-form">
          当前跟踪的mac地址：{{ trackingDeviceId }}
        </div>

        <!-- 中间部分 -->
        <div class="popup-middle">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="realCurrent" style="height: 220px"></div>
          </div>
        </div>

        <!-- 修改表格部分 -->
        <div class="table-container">
          <el-table
            :data="newTableData"
            stripe
            style="width: 100%; margin-top: 20px"
            row-key="id"
            height="250"
            :row-class-name="rowClassName"
          >
            <el-table-column
              label="时间"
              prop="time"
              width="150"
              align="center"
            ></el-table-column>
            <el-table-column
              label="当前网络模式"
              prop="nTtype"
              width="150"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.nTtype == 1">WIFI</span>
                <span v-else-if="scope.row.nTtype == 2">4G专线</span>
                <span v-else-if="scope.row.nTtype == 3">广域网专线</span>
              </template>
            </el-table-column>
            <el-table-column
              label="继电器开关"
              prop="jdqStatus"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.jdqStatus == 1">开</span>
                <span v-else-if="scope.row.jdqStatus == 0">关</span>
              </template>
            </el-table-column>
            <el-table-column
              label="电流（A）"
              prop="curr"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              label="电压（V）"
              prop="voltage"
              width="120"
              align="center"
            ></el-table-column>
            <el-table-column
              label="平均功率（W）"
              prop="power"
              width="120"
              align="center"
            ></el-table-column>

            <el-table-column
              label="提示列"
              prop="msg"
              width="420"
              align="center"
            ></el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer-right">
          <el-button type="warning" @click="setNetWOrkTypeByVue(1)">
            网络切换到WiFi
          </el-button>
          <el-button type="warning" @click="setNetWOrkTypeByVue(2)">
             网络切换到4G
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-setting"
            @click="elasticityDiag = true"
          >
            弹性配置
          </el-button>
          <!-- <el-button type="primary" @click="addNewRow">添加新行</el-button> -->
          <el-button @click="trackingPopupVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 弹性配置的弹出层 -->
    <el-dialog title="弹性条件配置" width="30%" :visible.sync="elasticityDiag">
      <el-form label-width="100px">
        <el-form-item label="电压(毫伏)">
          <el-input type="text" v-model="elasticity.voltageValue"></el-input>
        </el-form-item>
        <el-form-item label="电流(毫安)">
          <el-input type="text" v-model="elasticity.currValue"></el-input>
        </el-form-item>
        <el-form-item label="功率(毫瓦)">
          <el-input type="text" v-model="elasticity.powerValue"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="setElasticityValue()">发送</el-button>
        <el-button @click="elasticityDiag = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getDevList,
  getDevCommands,
  sendDevMeterCommand,
  getDevMonitorParams,
  setDevMonitorParams,
  sendLineCommand,
  editIsTop,
  queryBycurr,
  setTxValue,
  delBycurr,
  setNetWOrkTypeValue,
} from "@/api/alm/dev-base-info/dev-base-info-manage/dev-base-info-manage";
import {
  getAreaList,
  getAreaInfo,
} from "@/api/alm/statistical-export/area-manage/area-manage";
import {
  findChildrenByMac,
  findChildrenDataByMac,
} from "@/api/alm/dev-use-power/dev-realtime-info/dev-realtime-info";
import { getType } from "@/api/devTypeMap";
import { getGroupDict } from "@/api/alm/dev-group/dev-group";
import { getDevExNotViewedByMac } from "../../../../api/alm/dev-exception/dev-exception";
import * as echarts from "echarts";
export default {
  data() {
    return {
      showByteCommandDialog: false,
      devList: [],
      exInfoList: [],
      showExInfo: false,
      exFlashKey: true,
      cmd: {
        deviceId: "",
        commandIdAndType: "",
      },
      param: {
        deviceId: "",
        paramIdList: [],
        userInputValueList: [],
      },
      devCommandList: [],
      devParamMap: {},
      devParamList: [],
      devMonitorParamDialog: false,
      inputList: [],
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ipaddr: undefined,
        userName: undefined,
        status: undefined,
      },
      dateRange: [],
      lineList: [],
      tableId: 1,
      areaInfoList: [],
      groupDict: [],
      isTopMap: {},
      trackingPopupVisible: false,
      // 新增当前追踪的设备编号
      trackingDeviceId: null,
      // 新增是否全屏状态
      isFullScreen: false,
      //新增图表
      trackingTB: [],
      realDataMac: undefined,
      elasticityDiag: false,
      elasticity: {
        currValue: "",
        voltageValue: "",
        powerValue: "",
        devMac: "",
      },
      currenttb: null,
      voltagetb: null,
      powertb: null,
      resizeHandlers: {},
      newTableData: [],
      newRowId: 0,
    };
  },

  computed: {
    computedIsTop() {
      return function (value) {
        return this.isTopMap.get(value);
      };
    },
    selectedLabel() {
      const item = this.optionsTX.find(
        (opt) => opt.value === this.selectedValue
      );
      return item ? item.label : "";
    },
  },

  created() {
    this.isTopMap = new Map();
    this.isTopMap.set("N", "否");
    this.isTopMap.set("Y", "是");
    this.getDevGroupDict();
    this.getDevList();
    this.getAreaInfoList();
  },
  deactivated() {},
  mounted() {
    //添加socket通知监听
    window.addEventListener("onmessageWS", this.getSocketData);
  },

  methods: {
    // 实时跟踪弹出层
    openTrackingPopup(deviceId, onlineStatus) {
      this.trackingDeviceId = deviceId;
      this.realDataMac = deviceId;
      this.trackingPopupVisible = true;
      this.oneLoading({ mac: deviceId });
      // this.resetRealPower();
      // this.resetRealVoltage();
      this.resetRealCurrent();
      this.trackingTB = [];
      this.newTableData = [];
    },
    setElasticityValue() {
      this.elasticity.devMac = this.trackingDeviceId;
      setTxValue(this.elasticity).then((response) => {
        if (response.code == 200) {
          this.$message.success("配置成功！");
          this.elasticityDiag = false;
        } else {
          this.elasticityDiag = false;
          this.$message.success("配置失败！");
        }
      });
    },
    setNetWOrkTypeByVue(type) {
      setNetWOrkTypeValue({ devMac: this.trackingDeviceId, type: type }).then(
        (response) => {
          console.log(response);
        }
      );
    },
    loadTBData(time, nTtype, jdqStatus, curr, voltage, power, msg) {
      this.getRealCurrent();
      this.addNewRow(time, nTtype, jdqStatus, curr, voltage, power, msg);
    },
    addNewRow(time, nTtype, jdqStatus, curr, voltage, power, msg) {
      const newRow = {
        time: this.dateFormat(time / 1000),
        nTtype: nTtype,
        jdqStatus: jdqStatus,
        curr: curr,
        voltage: voltage,
        power: power,
        msg: msg,
        isNew: true,
      };
      this.newTableData.unshift(newRow);
    },
    rowClassName({ row }) {
      return row.isNew ? "new-row-highlight" : "";
    },
    clearTable() {
      this.newTableData = [];
    },
    //实时追踪代码结束
    //关闭弹出框
    handleDialogClose(deviceId) {
      delBycurr({ mac: this.realDataMac }).then((response) => {});
      this.realDataMac = undefined;
    },
    //更新电压电流
    addToTrackingTB(curr, power, voltage, BA, updateTime) {
      // 确保数据格式正确
      if (
        typeof curr === "undefined" ||
        typeof power === "undefined" ||
        typeof voltage === "undefined" ||
        typeof BA === "undefined"
      ) {
        console.error(
          "Invalid data format. Expected {curr, power, voltage, BA}"
        );
        return;
      }

      // 初始化数组（如尚未存在）
      if (!Array.isArray(this.trackingTB)) {
        this.trackingTB = [];
      }
      // 移除最早的数据（如果已达最大容量）
      if (this.trackingTB.length >= 5) {
        this.trackingTB.shift(); // FIFO：移除数组第一个元素
      }
      // 添加新数据
      this.trackingTB.push({
        curr: curr,
        power: power,
        voltage: voltage,
        BA: BA,
        modifyTime: updateTime, // 可选：添加时间戳用于调试
      });
      // Vue 的响应式更新提示（如需要）
      this.$forceUpdate();
    },
    // 收到消息处理
    getSocketData(res) {
      let message = JSON.parse(res.detail.data);
      if (message.data.msg === "ok") return;
      if (message.msgType == "SSDATA") {
        if (
          this.realDataMac != undefined &&
          message.data.devMac.toLowerCase() == this.realDataMac.toLowerCase()
        ) {
          var data = message.data;
          this.addToTrackingTB(
            data.curr,
            data.prower,
            data.voltage,
            data.Ab,
            data.updateTime
          );
          this.loadTBData(
            data.updateTime,
            data.nTtype,
            data.jdqStatus,
            data.curr,
            data.voltage,
            data.prower,
            ""
          );
        }
      }
      if (message.msgType == "SSDATALOGIN") {
        if (
          this.realDataMac != undefined &&
          message.data.devMac.toLowerCase() == this.realDataMac.toLowerCase()
        ) {
          var data = message.data;
          this.loadTBData(
            data.updateTime,
            data.nTtype,
            "",
            "",
            "",
            "",
            data.msg
          );
        }
      }
      if (message.msgType != "dev_ex") return;
      //若有设备在该页且有新异常
      let _this = this;
      // console.log(message.data.msg.slice(3, 15))
      let mac = message.data.msg.slice(3, 15);
      _this.devList.forEach((item) => {
        if (item.deviceId == mac) {
          item.hasNewEx = true;
        }
      });
      console.log(_this.devList);
      _this.devList = _this.devList.slice();
      console.log(_this.devList);
    },

    changeTop(isTop, devMac) {
      let editParams = {};
      editParams.isTop = isTop;
      editParams.devMac = devMac;
      console.log(editParams);
      editIsTop(editParams).then((res) => {
        if (res.code == 200) {
          this.queryParams.pageNum = 1;
          this.queryParams.pageSize = 10;
          this.getDevList();
        }
      });
    },
    // 初始化图表
    forMatterMapInfo(
      titleSubtext,
      xAxisData,
      yAxisAxisLabelFormatter,
      seriesData,
      randomColor,
      miny
    ) {
      return {
        title: {
          text: " ",
          subtext: titleSubtext,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          // prettier-ignore
          data: xAxisData,
        },
        yAxis: {
          type: "value",
          min: miny,
          axisLabel: {
            formatter: "{value} " + yAxisAxisLabelFormatter,
          },
          axisPointer: {
            snap: true,
          },
        },
        visualMap: {
          show: false,
          dimension: 0,
          pieces: [
            {
              gt: 0,
              lte: 19,
              color: randomColor,
            },
          ],
        },
        series: [
          {
            name: titleSubtext,
            type: "line",
            smooth: true,
            // prettier-ignore
            data: seriesData,
            markArea: {
              itemStyle: {
                color: "rgba(255, 173, 177, 0.4)",
              },
              data: [],
            },
          },
        ],
      };
    },
    // 重置电流图表
    resetRealCurrent() {
      if (this.currenttb) {
        this.currenttb.clear();
      }
    },
    // 重置电压图表
    resetRealVoltage() {
      if (this.voltagetb) {
        this.voltagetb.clear();
      }
    },
    // 重置功率图表
    resetRealPower() {
      if (this.powertb) {
        this.powertb.clear();
      }
    },
    initECharts(refName, chartName, title, unit, dataKey, defaultValue) {
      this.$nextTick(() => {
        // 检查 DOM 元素是否存在
        if (!this.$refs[refName]) {
          console.error(`${refName} DOM element not found`);
          return;
        }
        // 检查是否已初始化
        if (this[chartName] == null) {
          try {
            this[chartName] = echarts.init(this.$refs[refName], "macarons");
          } catch (e) {
            console.error(`ECharts init error for ${chartName}:`, e);
            return;
          }
        }
        let timeArr = [];
        let infoArr = [];
        const dataSource = this.trackingTB;
        if (dataSource) {
          try {
            dataSource.forEach((item) => {
              timeArr.push(this.dateFormat(item.modifyTime / 1000));
              infoArr.push(item[dataKey]);
            });
          } catch (e) {
            console.error(`Data processing error for ${chartName}:`, e);
            return;
          }
        }
        // 检查 this.forMatterMapInfo 是否存在
        if (!this.forMatterMapInfo) {
          console.error("forMatterMapInfo method not defined");
          return;
        }
        try {
          this[chartName].setOption(
            this.forMatterMapInfo(
              title,
              timeArr,
              unit,
              infoArr,
              "#93cd77",
              defaultValue
            ),
            true
          );
        } catch (e) {
          console.error(`ECharts setOption error for ${chartName}:`, e);
        }
        // 添加 resize 监听
        if (!this.resizeHandlers[chartName]) {
          this.resizeHandlers[chartName] = () => {
            this[chartName] && this[chartName].resize();
          };
          window.addEventListener("resize", this.resizeHandlers[chartName]);
          this.$once("hook:beforeDestroy", () => {
            window.removeEventListener(
              "resize",
              this.resizeHandlers[chartName]
            );
          });
        }
      });
    },
    // 加载电流
    getRealCurrent() {
      this.initECharts("realCurrent", "current", "当前电流", "A", "curr");
    },
    // // 加载电压
    // getRealVoltage() {
    //   this.initECharts("realVoltage", "voltage", "当前电压", "V", "voltage");
    // },
    // // 加载功率
    // getRealPower() {
    //   this.initECharts("realPower", "power", "当前功率", "W", "power");
    // },
    oneLoading(data) {
      queryBycurr(data).then((response) => {
        var data = response.data[0];
        this.addToTrackingTB(
          data.electricCurrent,
          data.frequency,
          data.voltage,
          data.powerFactor,
          data.modifyTime
        );
        this.loadTBData(
          response.data[0].modifyTime,
          response.data[0].networkType,
          response.data[0].relayStatus,
          response.data[0].electricCurrent,
          response.data[0].voltage,
          response.data[0].frequency,
          ""
        );
      });
    },
    //功率结束
    getDevList() {
      let _this = this;
      getDevList(_this.addDateRange(_this.queryParams, _this.dateRange)).then(
        (response) => {
          response.rows.forEach((item) => {
            item.tableId = _this.tableId++;
            item.energy = (item.energy + item.totalEnergy).toFixed(3);
            item.devType = item.sysDevInfo
              ? getType(item.sysDevInfo.devType)
              : "";
            item.devName = item.sysDevInfo ? item.sysDevInfo.devName : "";
            item.modifyTime = _this.dateFormat(item.modifyTime / 1000);
            item.hasChildren = item.lineNum > 1 ? true : false;
            item.hasNewEx = false;
          });
          _this.devList = response.rows;
          _this.total = response.total;
        }
      );
    },

    getDevCommands(obj) {
      getDevCommands(obj).then((response) => {
        this.devCommandList = response.data;
        this.showByteCommandDialog = true;
        console.log("this.devCommandList ", response.data);
      });
    },

    handleClick(row) {
      console.log(row);
    },

    getType(type) {
      return getType(type);
    },

    getDevGroupDict() {
      getGroupDict({}).then((res) => {
        this.groupDict = res.data;
      });
    },

    setExInfoDialog(item) {
      let obj = {};
      obj.mac = item.deviceId;
      getDevExNotViewedByMac(obj).then((res) => {
        this.exInfoList = res.data;
        this.exInfoList.forEach((element) => {
          element.occurTime = this.dateFormat(element.occurTime);
          // console.log(element.occurTime)
        });
      });
      this.showExInfo = true;
    },

    sendDevMeterCommand() {
      let arr = this.cmd.commandIdAndType.split(",");
      console.log("this.cmd ", this.cmd);
      let obj = {
        deviceId: this.cmd.deviceId,
        cmdId: Number(arr[0]),
        cmdType: arr[1] === "null" ? "" : arr[1],
        lineIdList: this.cmd.lineIdList,
      };

      if (this.cmd.lineIdList && this.cmd.lineIdList.length > 0) {
        sendLineCommand(obj).then((response) => {
          if (response.data) {
            this.$message.success("成功！");
            this.showByteCommandDialog = false;
          } else {
            this.$message.error("失败！");
          }
        });
      } else {
        sendDevMeterCommand(obj).then((response) => {
          if (response.data) {
            this.$message.success("成功！");
            this.showByteCommandDialog = false;
          } else {
            this.$message.error("失败！");
          }
        });
      }
      this.getDevList();
    },

    sendCharCommand(row) {
      this.cmd = {};
      this.cmd.deviceId = row.deviceId;
      if (row.hasChildren) {
        this.findChildrenByMac(row);
      }
      this.getDevCommands(this.cmd);
    },

    loadDevMonitorParams(row) {
      this.param = {};
      this.param.deviceId = row.deviceId;
      this.devMonitorParamDialog = true;

      getDevMonitorParams(row.deviceId).then((response) => {
        this.devParamMap = response.data;
        this.devParamList = [];

        for (let key in this.devParamMap) {
          if (this.devParamMap.hasOwnProperty(key)) {
            let arr = this.devParamMap[key];

            let paramObj = {
              label: key,
              options: [],
            };
            arr.forEach((item) => {
              paramObj.options.push({
                value: item.id,
                label: item.name,
              });
            });
            this.devParamList.push(paramObj);
          }
        }
      });
    },

    setDevMonitorParams() {
      this.param.userInputValueList = this.inputList;
      setDevMonitorParams(this.param).then((response) => {
        if (response.code == 200) {
          this.devMonitorParamDialog = false;
          this.$message.success("配置成功！");
        }
      });
    },

    addInput() {
      this.inputList = [];
      for (let key in this.devParamMap) {
        if (this.devParamMap.hasOwnProperty(key)) {
          let objArr = this.devParamMap[key];
          objArr.forEach((item) => {
            this.param.paramIdList.forEach((item2) => {
              if (item.id === item2) {
                this.inputList.push(item);
              }
            });
          });
        }
      }
    },

    opendg(row) {},

    opentx(row) {},

    submitSearchForm() {
      console.log(this.queryParams);
      this.getDevList(this.queryParams);
    },

    resetForm() {
      this.$refs["elForm"].resetFields();
      this.dateRange = [];
      this.queryParams.pageNum = 1;
      this.getDevList();
    },

    dateFormat(timeStamp) {
      // 创建一个新的Date对象，将时间戳作为参数传递给构造函数
      const date = new Date(timeStamp * 1000);
      // 获取年、月、日、小时和分钟
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      // 重新赋值格式化后的日期字符串
      return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    },

    loadDevLine(tree, treeNode, resolve) {
      let _this = this;
      setTimeout(() => {
        findChildrenDataByMac(tree.deviceId).then((response) => {
          _this.lineList = response.rows ? response.rows : [];
          _this.lineList.forEach((item) => {
            item.optBut = true;
            item.deviceId = "第" + item.lineNo + "路";
            item.tableId = _this.tableId++;
            item.devInTheArea = tree.devInTheArea;
            item.onlineStatus = tree.onlineStatus;
            item.networkType = tree.networkType;
            item.voltage = tree.voltage;
          });
          resolve(_this.lineList);
        });
      }, 1000);
    },

    findChildrenByMac(obj) {
      let _this = this;
      findChildrenByMac(obj.deviceId).then((response) => {
        _this.lineList = response.rows ? response.rows : [];
        _this.lineList.forEach((item) => {
          item.optBut = true;
          item.deviceId = "第" + item.lineNo + "路";
          item.tableId = _this.tableId++;
        });
      });
    },

    getAreaInfoList() {
      getAreaList({}).then((response) => {
        this.areaInfoList = response.data;
      });
    },
  },
};
</script>

<style scoped>
.main {
  width: 100%;
}
</style>